package cn.donting.jme.utile;

import cn.hutool.core.io.FileUtil;
import com.jme3.material.MatParam;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.math.Vector4f;
import com.jme3.shader.VarType;

import java.io.File;
import java.util.Collection;

/**
 * j3m 转化工具
 */
public class J3mUtil {

    private static final String tem = "Material {name} : {def} {\n" +
            "     MaterialParameters {\n" +
            "{parameters}" +
            "     }\n" +
            "}";

    /**
     * 将material 转化为 j3m 文件
     * @param material
     * @return
     */
    public static String toJ3mText(Material material) {
        String name = material.getName();
        String j3m = tem.replace("{name}", name);
        j3m = j3m.replace("{def}", material.getMaterialDef().getAssetName());
        Collection<MatParam> params = material.getParams();
        StringBuilder parameters = new StringBuilder();
        for (MatParam param : params) {
            String paramText = param.getName() + " : " + readValueText(param);
            parameters.append("         ").append(paramText).append("\n");
        }
        j3m = j3m.replace("{parameters}", parameters.toString());
        return j3m;
    }

    private static String readValueText(MatParam param) {
        VarType varType = param.getVarType();
        Object value = param.getValue();
        if (varType==VarType.Vector2) {
            Vector2f v = (Vector2f) value;
            return v.x+" "+v.y+" ";
        }
        if (varType==VarType.Vector3) {
            Vector3f v = (Vector3f) value;
            return v.x+" "+v.y+" "+v.z;
        }
        if (value instanceof ColorRGBA) {
            ColorRGBA v = (ColorRGBA) value;
            return v.r+" "+v.g+" "+v.b+" "+v.a;
        }
        if (varType==VarType.Vector4) {
            Vector4f v = (Vector4f) value;
            return v.x+" "+v.y+" "+v.z+" "+v.w;
        }

        return value.toString();
    }
}
